/************************************************************************

								Heroes IV
					  Copyright 2001, The 3DO Company

	------------------------------------------------------------------
  						 combat_ai_ranged_area_action.cpp

	$Header: $

	$NoKeywords: $

 ************************************************************************/

// kill the 255+ character identifier warning.  Templates tend to exceed that easily.
#include "precompiled.h"
#pragma warning( disable: 4786 )

#include "combat_ai_ranged_area_action.h"

#include <sstream>
#include "area_effect_point.h"
#include "battlefield.h"
#include "combat_ai.h"
#include "debug_message.h"


void t_combat_ai_ranged_area_action::weigh_action(class t_combat_ai const& owner)
{
	if (has_been_weighed())
		return;

	t_battlefield &battlefield = m_battlefield;

	t_combat_creature const& attacker = owner.get_actor();

	t_combat_creature_set const&	affected_list = m_point->get_affected_list();
	double							total = 0.0;
		
	for (t_combat_creature_set::const_iterator affected_iterator = affected_list.begin(); affected_iterator != affected_list.end(); affected_iterator++)
	{
		const t_combat_creature &affected = **affected_iterator;
	
		int damage = attacker.get_ranged_damage( affected, 0, 0 );
		double weight = affected.get_ai_value( damage );

		weight += t_combat_ai::get_zoc_change_weight(damage, affected, false, 0);

		if (affected.belongs_to_defender() == attacker.get_controller())
		{
			weight *= -weight;
		}

		total += weight;
	}
	set_weight( total );
}

void t_combat_ai_ranged_area_action::perform_action(void)
{
	t_battlefield &battlefield = m_battlefield;


	// Choose a random point to attack from the list
	t_map_point_2d attack_point;
	int point_count = 0;

	const t_map_point_2d_list &point_list = m_point->get_point_list();

	assert(!point_list.empty());

	t_map_point_2d_list::const_iterator point_iterator;

	for (point_iterator = point_list.begin(); point_iterator != point_list.end(); point_iterator++)
	{
		point_count++;

		if (random(point_count) == 0)
		{
			attack_point = *point_iterator;
		}
	}

	battlefield.begin_ranged_attack( attack_point );
}
